//
//  GXCycleImages.m
//  16-UICollectionViewCycleImage
//
//  Created by 曹曹 on 16/8/4.
//  Copyright © 2016年 曹曹. All rights reserved.
//

#import "GXCycleImages.h"

#define kCollectionViewCellReuse @"cellReuse"
#define kArc4RandomColor [UIColor colorWithRed:arc4random() % 256 / 255.0f green:arc4random() % 256 / 255.0f blue:arc4random() % 256 / 255.0f alpha:1]

@interface GXCycleImages () <UICollectionViewDelegate, UICollectionViewDataSource>
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UIPageControl *pageControl;
@property (nonatomic, strong) UICollectionViewFlowLayout *flowLayout;
@property (nonatomic, strong) NSTimer *timer;
@end

@implementation GXCycleImages

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor redColor];
        [self setUp];
    }
    return self;
}
// SB中创建控件时走下边的方法(读取本地SB,xib等文件)
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        self.backgroundColor = [UIColor redColor];
        [self setUp];
        // NSLog(@"%lf", self.frame.size.width);/**< 打印结果为0 */
    }
    return self;
}

- (void)setUp {
    [self createCollectionView];
    [self createPageControl];
//    [self createLabel];
    [self addTimer];
}

- (void)createCollectionView {
    _flowLayout = [[UICollectionViewFlowLayout alloc] init];
    _flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    _flowLayout.minimumLineSpacing = 0;
    _flowLayout.minimumInteritemSpacing = 0;
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:_flowLayout];
    _collectionView.pagingEnabled = YES;
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.showsHorizontalScrollIndicator = NO;
    [self addSubview:_collectionView];
    [_collectionView registerClass:[GXCycleImagesCell class] forCellWithReuseIdentifier:kCollectionViewCellReuse];
}

- (void)createPageControl {
    _pageControl = [[UIPageControl alloc] initWithFrame:CGRectZero];
    _pageControl.currentPageIndicatorTintColor = [UIColor redColor];
    _pageControl.pageIndicatorTintColor = [UIColor lightGrayColor];
    [self addSubview:_pageControl];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _imagesArray.count;
}

- (void)createLabel {
    _label = [[UILabel alloc] initWithFrame:CGRectZero];
    [self addSubview:_label];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    self.cell = [collectionView dequeueReusableCellWithReuseIdentifier:kCollectionViewCellReuse forIndexPath:indexPath];
    self.cell.imageView.image = [UIImage imageNamed:_imagesArray[indexPath.row]];
    // 点击方法
    // nstimer
    // 定制
    if (self.dataSource && [self.dataSource respondsToSelector:@selector(handleDataWithObject:cell:)]) {
        [self.dataSource handleDataWithObject:_imagesArray[indexPath.row] cell:self.cell];
    }
    return _cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if ([self.cycleDelegate respondsToSelector:@selector(collectionView:didSelectItem:AtIndexPath:)]) {
        [self.cycleDelegate collectionView:collectionView didSelectItem:self.cell AtIndexPath:indexPath];
    }
}

- (void)layoutSubviews {
    [super layoutSubviews];
    // NSLog(@"%lf", self.frame.size.width);/**< 正常宽度 */
    _collectionView.frame = self.bounds;
    _flowLayout.itemSize = self.bounds.size;
    [_collectionView setContentOffset:CGPointMake(self.bounds.size.width, 0)];
    _pageControl.frame = CGRectMake(0, 0, 100, 20);
    _pageControl.center = CGPointMake(CGRectGetWidth(self.bounds) / 2, CGRectGetHeight(self.bounds) - 10);
    _pageControl.numberOfPages = _imagesArray.count - 2;
    [_pageControl addTarget:self action:@selector(changeImage:) forControlEvents:UIControlEventValueChanged];
    _label.frame = CGRectMake(0, 0, 200, 30);
    _label.center = CGPointMake(CGRectGetWidth(self.bounds) / 2, 20);
    _label.textAlignment = NSTextAlignmentCenter;
}

- (void)changeImage:(UIPageControl *)pageControl {
    _collectionView.contentOffset = CGPointMake(CGRectGetWidth(self.bounds) * (_pageControl.currentPage + 1), 0);
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    // 直接判断与0相等有何问题
    if (scrollView.contentOffset.x <= 1) {
        [_collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:_imagesArray.count - 2 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    } else if (scrollView.contentOffset.x >= _collectionView.bounds.size.width * (_imagesArray.count - 1) - 1) {
        [_collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:1 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    }
    NSInteger page = _collectionView.contentOffset.x / self.bounds.size.width;
    _pageControl.currentPage = page - 1;
}

- (void)addTimer {
    NSLog(@"reAdd");
    // 创建一个timer, 并添加到loop中
    // self.timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(xchImage:) userInfo:nil repeats:YES];
    /** --------------------- */
    // 仅仅是创建, 并没有加到loop中
    _timer = [NSTimer timerWithTimeInterval:2 target:self selector:@selector(xchImage:) userInfo:nil repeats:YES];
    // NSDefaultRunLoopMode默认状态,scheduledTimerWithTimeInterval添加为默认状态
    // NSRunLoopCommonModes多种状态, 包含默认和滚动
    [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
    
}

- (void)removeTimer {
    NSLog(@"remove");
    [self.timer invalidate];
    _timer = nil;
}

- (void)xchImage:(NSTimer *)timer {
    int page = (int)self.pageControl.currentPage;
    if (page == _imagesArray.count - 3) {
        page = 0;
    } else {
        page++;
    }
    [self.collectionView setContentOffset:CGPointMake((page + 1) * CGRectGetWidth(self.bounds), 0)];
    _pageControl.currentPage = page;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self removeTimer];
    
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [self addTimer];
}


- (void)setImagesArray:(NSMutableArray *)imagesArray {
    _imagesArray = imagesArray;
    [_collectionView reloadData];
}

- (void)setLabel:(UILabel *)label {
    _label = label;
    [_collectionView reloadData];
}

@end

/**
 GXCycleImagesCell
 */
@implementation GXCycleImagesCell

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        _imageView = [[UIImageView alloc] initWithFrame:CGRectZero];
        _label = [[UILabel alloc] initWithFrame:CGRectZero];
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    _imageView.frame = self.bounds;
    _label.frame = CGRectMake(0, 0, 200, 30);
    _label.center = CGPointMake(CGRectGetWidth(self.bounds) / 2, 20);
    _label.textAlignment = NSTextAlignmentCenter;
    [self.contentView addSubview:_imageView];
    [self.contentView addSubview:_label];
}

- (void)setLabel:(UILabel *)label {
    _label = label;
}



@end
